import axios from "axios";
import { ElMessage, tourContentEmits } from "element-plus";
import VueCookie from 'vue-cookie'
import router from '@/router'
//export才能共享


export const _axios = axios.create({
    baseURL: 'http://localhost:8080', // 设置基地址
});


import { userLoadingStore } from '@/stores'
const userLoading = userLoadingStore()

_axios.interceptors.request.use(config => {
	const token = VueCookie.get('token')
	if(token){
		config.headers.token = token
	}
	return config
},error => {
	return Promise.reject(error)
})



export const request = (url, method, params, callback) => {
    // 封装数据
    const axiosConfig = {
        url,
        method
    }
    // 如果是post请求则转化为 FormData格式
    if (method == 'post') {
    	const formData = new FormData()
    	for(let key in params) {
    		if (params[key] instanceof Array) {
    			for (const i in params[key]) {
    				formData.append(key, params[key][i])
    			}
    		} else {
    			formData.append(key, params[key])
    		}
    	}
    	//如果没有这个属性 就创建然后赋值
    	axiosConfig.data = formData
    	console.dir(formData)
        console.dir("位置1")
    }else{
        axiosConfig.params = params
        console.dir("位置2")
    }
    console.dir("位置3")
    // 发送请求
    userLoading.setLoading(true)
    console.dir("位置4")
    _axios.request(axiosConfig).then(response => {
        console.dir("位置5")
        //如果请求成功
        if(response.data.code === 200) {console.dir("位置6")
            // message 有内容
            if(response.data.message) {console.dir("位置7")
                ElMessage.success(response.data.message)
            }
            //回调函数内容
            callback(response.data.content)
        }else {//请求失败 提示失败信息
            ElMessage.error(response.data.message)
            console.dir("位置8")
            console.dir(response.data)
            router.push({
                path: '/lunbo'
            })
            console.dir("位置8.1")
			if(response.data.code === 401){
				router.push({
					path: '/'
				})
                console.dir("位置9")
                console.dir("axios.js:请求失败")
			}
        }
    }).catch(error => {
        console.dir(error)
        console.dir("位置10")
    }).finally(() => {
        userLoading.setLoading(false)
    })
}

//进一步封装get和post请求
export const get = (url, params, callback) => {
    request(url, 'get', params, callback)
}
export const post = (url, params, callback, formObj = null) => {
    if(formObj) {// 是否有表单验证
        formObj.value.validate(valid => {
            if(valid) {//如果校验通过 发请求
                request(url, 'post', params, callback)
            }
        })
    }else{
        request(url, 'post', params, callback)
    }
}

